package com.hliushi.hotel.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hliushi.hotel.constants.MqConstants;
import com.hliushi.hotel.entity.Hotel;
import com.hliushi.hotel.entity.PageResult;
import com.hliushi.hotel.service.IHotelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.InvalidParameterException;

@Slf4j
@RestController
@RequestMapping("/hotel")
public class HotelController {

    @Resource
    private IHotelService hotelService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/{id}")
    public Hotel queryById(@PathVariable("id") Long id) {
        log.info("=================== 调用了queryById, id : {}", id);
        return hotelService.getById(id);
    }


    /**
     * 查询列表, 可以附加条件 模糊查询
     *
     * @param key 输入的关键字 模糊匹配 name/address/business 字段
     * @return PageResult
     */
    @GetMapping("/list")
    public PageResult hotelList(
            @RequestParam("query") String key,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "1") Integer size) {

        /**
         * MP的构造器之动态SQL
         * boolean condition 判断条件, true 才会将条件拼接到SQL中
         * public Children like(boolean condition, R column, Object val)
         */

        Page<Hotel> result = hotelService.page(new Page<>(page, size), Wrappers.<Hotel>lambdaQuery()
                .like(StringUtils.isNotBlank(key), Hotel::getName, key)
                .or()
                .like(StringUtils.isNotBlank(key), Hotel::getAddress, key)
                .or()
                .like(StringUtils.isNotBlank(key), Hotel::getBusiness, key));
        log.info("=================== result : {}", result.getRecords());
        return new PageResult(result.getTotal(), result.getRecords());
    }

    @PostMapping
    public void saveHotel(@RequestBody Hotel hotel) {
        hotelService.save(hotel);

        // 发送消息,    优化 -> 只发送id过去, 减少mq持久化和内存占用带来的问题
        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_INSERT_KEY, hotel.getId());
    }

    @PutMapping()
    public void updateById(@RequestBody Hotel hotel) {
        if (hotel.getId() == null) {
            throw new InvalidParameterException("id不能为空");
        }
        hotelService.updateById(hotel);
        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_INSERT_KEY, hotel.getId());
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        hotelService.removeById(id);
        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_DELETE_KEY, id);
    }
}
